<template>
  <div class="p-5 space-y-4">
    <p class="mt-4"> 姓名： </p>
    <p class="mt-4">
      <a-input v-model:value="keyWord" />
    </p>
    <p>年龄：</p>
    <a-input v-model:value="age" />
    <p>爱好：</p>
    <p class="flex">
      <a-input v-model:value="hobby" placeholder="输入多个时使用 / 分隔" />
      <a-button type="primary" @click="handleAddData" class="ml-4">添加</a-button>
    </p>
    <a-input-search placeholder="查询爱好" @search="getHobby" />
    <a-input-search placeholder="查询多个爱好" @search="getHobbyMs" />
    <a-table
      :pagination="false"
      row-key="id"
      :row-selection="{
        selectedRowKeys,
        onChange: onSelectChange,
      }"
      :data-source="dataSource"
      :columns="[
        { title: '主键', dataIndex: 'id' },
        { title: '姓名', dataIndex: 'name' },
        { title: '年龄', dataIndex: 'age' },
        { title: '爱好', dataIndex: 'hobby' },
      ]"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'hobby'">
          {{ record.hobby.join(' | ') || '-' }}
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
  import { db } from './db';
  import { ref } from 'vue';

  const keyWord = ref('');
  const age = ref('');
  const hobby = ref('');
  const dataSource = ref([]);
  const selectedRowKeys = ref([]);

  function onSelectChange(keys, rows) {
    selectedRowKeys.value = keys;
  }

  async function getAllData() {
    const res = await db.user.toArray();
    dataSource.value = res;
  }

  getAllData();

  async function handleAddData() {
    const id = await db.user.add({
      name: keyWord.value,
      age: age.value,
      hobby: hobby.value.split('/'),
    });
    getAllData();
  }

  // 根据输入的爱好 查询所有匹配的用户信息
  async function getHobby(value) {
    // 同一个用户信息中，可能会匹配多次
    // 使用distinct方法过滤掉同一个数据
    const res = await db.user.where('hobby').equals(value).distinct().toArray();
    console.log(res);
  }

  // 只要anyOf中有一项匹配的值在用户信息中就能被查询出来
  async function getHobbyMs(value) {
    console.log(value);
    value = value.trim().split('/') || [];
    const res = await db.user.where('hobby').anyOf(value).toArray();
    console.log(res);
  }

  //  https://blog.csdn.net/qq_36587420/article/details/105058830
</script>
